package ru.common;

import java.io.CharArrayWriter;
import java.io.Writer;

import org.codehaus.jackson.map.ObjectMapper;

public final class Jsons {

    public static String serialize(Object model) {
        CharArrayWriter chars = new CharArrayWriter();
        serialize(model, chars);
        return chars.toString();
    }

    public static void serialize(Object model, Writer writer) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            mapper.writeValue(writer, model);
            writer.flush();
        } catch (Exception e) {
            throw new IllegalStateException();
        }
    }

    public static <T> T unserialize(String json, Class<T> valueType) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            T value = mapper.readValue(json, valueType);
            return value;
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    private Jsons() {
    }

}
